<?php
namespace Drawping\CarApi;

use GuzzleHttp\Client as HttpClient;

class Application
{
    protected $config = [];
    protected $client;

    function __construct($config)
    {
        $this->config = $config;
    }

    function getBrands(){
        $client = new HttpClient();
        $response = $client->request('GET', 'http://api.jisuapi.com/car/brand?appkey='.$this->config['appkey']);
        if ($response->getStatusCode() !== 200) {
            Log::info('jisuapi_error_http:'.(string)$response->getStatusCode());
            return false;
        }

        $body = $response->getBody();
        $r = $this->parseJSON($body);

        if($r->status != 0){
            return false;
        }
        return $r->result;
    }

    function getSerie($parentid = 0){
        $client = new HttpClient();
        $response = $client->request('GET', 'http://api.jisuapi.com/car/carlist?appkey='.$this->config['appkey'].'&parentid='.$parentid);
        if ($response->getStatusCode() !== 200) {
            return false;
        }

        $body = $response->getBody();
        $r = $this->parseJSON($body);

        if($r->status != 0){
            return false;
        }

        return $r->result;
    }

    public function parseJSON($body)
    {
        $body = $this->fuckTheWeChatInvalidJSON($body);
        if (empty($body)) {
            return false;
        }
        $contents = json_decode($body);
        return $contents;
    }

    protected function fuckTheWeChatInvalidJSON($invalidJSON)
    {
        return preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', trim($invalidJSON));
    }

}